package com.example.skycode6.servlet;

import com.example.skycode6.bean.NewsBean;
import com.example.skycode6.dao.NewsDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/newsAdd.jsp")
public class NewsAddServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        HttpSession session = req.getSession();
        String User = (String) session.getAttribute ("user");
        if (User == null || User.equals("")) {
            resp.sendRedirect ("login.jsp");
        }
        req.setCharacterEncoding("UTF-8");
        NewsBean newsBean = new NewsBean();
        String title = req.getParameter("NewsTitle");
        String content = req.getParameter("NewsContent");
        newsBean.setNewsTitle(title);
        newsBean.setNewsContent(content);
        newsBean.setAdminName("admin");// 更换为登录的管理员名称
        // 添加
        NewsDao newsDao = new NewsDao();
        int result = newsDao.add(newsBean); // 返回受影响的行
        if(result>0){
            resp.sendRedirect("news.jsp");
        }else{ // 失败跳转错误页面 显示错误信息 并回到指定页面
            req.setAttribute("msg","添加失败");
            req.setAttribute("url","news.jsp");// 提示信息后返回的页面
            req.getRequestDispatcher("WEB-INF/error.jsp").forward(req,resp);
        }
    }
}
